package com.ecity.util {
	import com.ecity.events.GameEvent;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.utils.clearTimeout;
	import flash.utils.setTimeout;
	
	/**
	 * ...
	 * @author ss
	 */
	public class Samulator extends Sprite {
		private var gridLine:Sprite = new Sprite();
		public static const CELL_W:int = 20;
		public static const CELL_H:int = 20;
		
		public function Samulator(){
			this.addEventListener(MouseEvent.CLICK, onMouseClick);
			this.graphics.beginFill(0x999999, 0);
			this.graphics.drawRect(0, 0, 1024, 768);
			this.graphics.endFill();
			initGrid();
		}
		
		private function onMouseClick(e:MouseEvent):void {
			var mx:int = Math.floor(mouseX / CELL_W);
			var my:int = Math.floor(mouseY / CELL_H);
			this.dispatchEvent(new GameEvent(GameEvent.SAMULATOR_CLICK, { mx:mx, my:my } ));
			this.drawRects(mx, my);
		}
		
		public function drawRects(X:int, Y:int,isHit:Boolean=false):void {
			var clr:uint = 0x00ff00;
			if (isHit) {
				clr = 0xff0000;
			}
			var s:Sprite = new Sprite();
			s.graphics.beginFill(clr,0.5);
			s.graphics.drawRect(X * CELL_W, Y*CELL_H, CELL_W, CELL_H);
			s.graphics.endFill();
			this.addChild(s);
			var st:uint = setTimeout(clearRects, 1000,s,st);
		}
		
		private function clearRects():void {
			var s:Sprite = arguments[0];
			s.graphics.clear();
			this.removeChild(s);
			clearTimeout(arguments[1]);
		}
		
		
		public function initGrid():void {
			var num:int = int(1020 / CELL_W);
			for (var i:int = 0; i < num*38; i++) {
				gridLine.graphics.lineStyle(0.5, 0x999999, 0.2);
				gridLine.graphics.drawRect((i % num) * CELL_W, int(i / num)*CELL_H, CELL_W, CELL_H);
				gridLine.graphics.endFill();
			}
			this.addChild(gridLine);
		}
		
	}

}